package org.je.ufo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fanyifeng
 */
public class PUtil
{
	/**
	 * @param path
	 * @return formated path
	 */
	public static String format(String path) {
		if (path == null) {
			throw new NullPointerException("url-is-null");
		}
		List<String> list = fastSplit(path);
		if (list.size() == 0) {
			return "/";
		}
		StringBuilder bf = new StringBuilder(64);
		bf.append("/");

		for (String s : list) {
			bf.append(s);
			bf.append("/");
		}
		if (bf.length() == 1) {
			return "/";
		}
		return bf.substring(0, bf.length() - 1);
	}

	private static List<String> fastSplit(String src) {
		List<String> list = new ArrayList<String>(8);
		int bg = 0;
		for (int i = 0; i < src.length(); ++i) {
			char c = src.charAt(i);
			if (c == '/' || c == '\\') {
				if (bg < i) {
					String s = src.substring(bg, i).trim();
					if (s.length() > 0) {
						list.add(s);
					}
				}
				bg = i + 1;
			}
		}

		if (bg < src.length()) {
			String s = src.substring(bg).trim();
			if (s.length() > 0) {
				list.add(s);
			}
		}
		return list;
	}
}
